const { sequelize } = require("../db/index")
const { DataTypes, Model } = require("sequelize")
const User = require("./user_model")
const Cleaner = require("./cleaner_model")
const moment = require("moment")

class GoodsAttrConfig extends Model {
  static async hasGoodsAttrConfig(id, goods_id) {
    const attr = await GoodsAttrConfig.findOne({ where: { id, goods_id } })
    if (attr === null) {
      return false
    } else {
      return true
    }
  }
  static async createGoodsAttrConfig({
    goods_id,
    attr_name,
    attr_values,
    is_delete
  }) {
    const data = await GoodsAttrConfig.create({
      goods_id,
      attr_name,
      attr_values,
      is_delete
    })
    return data
  }
  static async addAdmin(buildingId, userId) {
    try {
      const cate = await Cate.findOne({ where: { id: buildingId } })
      const user = await User.findOne({ where: { id: userId } })
      const result = await cate.addAdmin(user)
      return result
    } catch (e) {
      throw new Error("已存在该管理员，添加失败")
    }
  }
  static async addCleaner(buildingId, cleanerId) {
    try {
      const cleaner = await Cleaner.findOne({ where: { id: cleanerId } })
      cleaner.buildingId = buildingId
      return await cleaner.save()
    } catch (e) {
      throw new Error("添加保洁员失败")
    }
  }
  static async addFloor(buildingId, floor) {
    try {
      floor.buildingId = buildingId
      return await floor.save()
    } catch (error) {
      console.log(error)
    }
  }
}

GoodsAttrConfig.init(
  {
    goods_id: {
      comment: "商品ID",
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: false,
      allowNull: false
    },
    config: {
      comment: "规格值",
      type: DataTypes.STRING,
      autoIncrement: false,
      allowNull: false
    },
    update_time: {
      comment: "更新时间",
      type: DataTypes.STRING,
      get() {
        return moment(this.getDataValue("update_time")).format(
          "YYYY-MM-DD HH:mm:ss"
        )
      }
    }
  },
  {
    sequelize,
    modelName: "sp_store_goods_attr_config",
    freezeTableName: true,
    paranoid: false,
    timestamps: false
  }
)

GoodsAttrConfig.removeAttribute("id")

module.exports = GoodsAttrConfig
